package apbms

class ContaController {

    def index = {
        redirect(action: "show", params: params)
    }
    
    def show = {
        def usuInstance = session.usuario
        if (!usuInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'conta.label', default: 'Conta'), params.id])}"
            redirect(controller: "login", action:"login")
        }
        else {
            [usuInstance: usuInstance]
        }
    }
    
    def admin = {
        def user = session.usuario
        def usuInstance = Usuario.get(user.id)
        def reconfSenha = new String()
        if (!usuInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'conta.label', default: 'Conta'), params.id])}"
            redirect(controller: "login", action:"login")
        }
        else {
            [usuInstance: usuInstance]
        }
    }
    
    def alterar = {
        def usuInstance = Usuario.get(params.id)
        def reconfSenha = params.confirmacao
        if(usuInstance){
            if(params.version){
                def version = params.version.toLong()
                if(usuInstance.version > version){
                    return
                }
            }
            usuInstance.properties = params
            if(!reconfSenha.equals(usuInstance.senha)){
                flash.message = "Os campos senha e reconfirmação estão diferentes"
                redirect(action: "admin", id: usuInstance.id)
                return
            }
            usuInstance.senha = params.senha.encodeAsSenha()
            if(!usuInstance.hasErrors() && usuInstance.save(flush: true)){
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'conta.label', default: 'Conta'), dependenteInstance.id])}"
                redirect(action: "show", id: usuInstance.id)
            }
        }else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'conta.label', default: 'Conta'), params.id])}"
            redirect(controller:'login', action: "login")
        }
    }
}
